package xyz.missou.blog.filter;

import xyz.missou.blog.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "ManageFilter", urlPatterns = {"/manage/*"})
public class ManageFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;//将request强制转换为HttpServletRequest类型
        HttpServletResponse res = (HttpServletResponse) response;//将response强制转换为HttpServletResponse类型

        HttpSession session = req.getSession();//获得一个Session对象，用于存放一些提示信息返回到前台或者获取Session对象中的信息
        //从session中取出user对象（该对象在登录成功后放入session）
        User user = (User) session.getAttribute("user");
        //如果用户登录成功并且登录用户为管理员类型，将继续执行用户请求操作，否则返回越权操作或者未登录提示信息并跳转到系统首页或者登录页面
        if (user == null) {
            //未登录成功将返回用户没有登录提示信息并跳转到系统登录页面
            res.sendRedirect(req.getContextPath() + "/user/login/");
        } else if (user.getIsManage()==0){
            res.sendRedirect(req.getContextPath() + "/user/nopowertomanage/");
        } else {
            chain.doFilter(req, res);//继续执行用户请求的操作
        }

    }

    @Override
    public void destroy() {

    }

}
